package com.donger.sso.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.HttpStatus;
import com.donger.common.core.utils.Res;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author pmc
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;

    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/sso/**", "/oauth2/**", "/sa-res/**", "/login", "/admin/**", "/")
                .setAuth(obj -> {
                    if (!StpUtil.isLogin()) {
                        try {
                            SaHolder.getResponse().setStatus(HttpStatus.HTTP_UNAUTHORIZED);
                            String err = objectMapper.writeValueAsString(Res.error("登录失败"));
                            SaRouter.back(err);
                        } catch (JsonProcessingException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    /**
     * 密码校验
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

}
